const baseURL = 'http://localhost:8080';

export const request = async (options) => {
	const {
		url,
		method = 'GET',
		data,
		headers = {},
		auth = true // 默认需要认证
	} = options;

	// 设置请求头
	const mergedHeaders = {
		'Content-Type': 'application/json',
		...headers
	};

	// 添加认证头
	if (auth) {
		const token = uni.getStorageSync('token');
		if (token) {
			mergedHeaders.Authorization = token;
		}
	}

	try {
		const res = await uni.request({
			url: `${baseURL}${url}`,
			method,
			data,
			header: mergedHeaders
		});

		// 请求成功但业务逻辑失败
		if (res.statusCode !== 200 || (res.data.code && res.data.code !== 200)) {
			const error = new Error(res.data.msg || '请求失败');
			error.response = res;
			throw error;
		}

		return res.data;
	} catch (error) {
		// 统一错误处理
		console.error('Request Error:', error);
		uni.showToast({
			title: error.message || '网络请求失败',
			icon: 'none'
		});
		throw error;
	}
};
